using System.IO;
using UnityEngine;
using UnityEngine.Tilemaps;
using System.Collections.Generic;
using GameLogic;

using Newtonsoft.Json;


#if UNITY_EDITOR
using UnityEditor;
#endif

[ExecuteInEditMode]
public class GridMap : MonoBehaviour
{
    public MapData_SO mapData;
    public GridType gridType;
    private Tilemap currentTilemap;
    private static string SavePath => Path.Combine(Application.persistentDataPath, "TileMapData.json");

    private void OnEnable()
    {
        if (!Application.IsPlaying(this))
        {
            currentTilemap = GetComponent<Tilemap>();

            if (mapData != null)
                mapData.tileProperties.Clear();
        }
    }

    private void OnDisable()
    {
        if (!Application.IsPlaying(this))
        {
            currentTilemap = GetComponent<Tilemap>();
            UpdateTileProperties();

            // 保存为JSON文件
            SaveMapDataToJson(this.mapData);
        }
    }

    private void UpdateTileProperties()
    {
        currentTilemap.CompressBounds();

        if (!Application.IsPlaying(this) && mapData != null)
        {
            // 已绘制范围的左下角坐标
            Vector3Int startPos = currentTilemap.cellBounds.min;
            // 已绘制范围的右上角坐标
            Vector3Int endPos = currentTilemap.cellBounds.max;

            for (int x = startPos.x; x < endPos.x; x++)
            {
                for (int y = startPos.y; y < endPos.y; y++)
                {
                    TileBase tile = currentTilemap.GetTile(new Vector3Int(x, y, 0));

                    if (tile != null)
                    {
                        TileProperty newTile = new TileProperty
                        {
                            tileCoordinate = new Vector2Int(x, y),
                            gridType = this.gridType,
                            boolTypeValue = true
                        };

                        mapData.tileProperties.Add(newTile);
                    }
                }
            }
        }
    }

    private void SaveMapDataToJson(MapData_SO mapData)
    {
        if (mapData == null) return;

        // 创建可序列化的数据对象
        MapDataJson jsonData = new MapDataJson
        {
            gridWidth = mapData.gridWidth,
            gridHeight = mapData.gridHeight,
            originX = mapData.originX,
            originY = mapData.originY,
            tileProperties = mapData.tileProperties
        };

        Dictionary<string, MapDataJson> mapDataList = new Dictionary<string, MapDataJson>();
        mapDataList.Add(mapData.sceneName,jsonData);

        string json = JsonConvert.SerializeObject(mapDataList, Formatting.Indented);
        File.WriteAllText(SavePath, json);

        Debug.Log($"地图数据已保存到: {SavePath}");
    }
}

[System.Serializable]
public class MapDataJson
{
    public int gridWidth;
    public int gridHeight;
    public int originX;
    public int originY;
    public List<TileProperty> tileProperties;
}